package online.afeibaili.storebackendframework.service.impl

import online.afeibaili.storebackendframework.model.OrderEntity
import online.afeibaili.storebackendframework.model.PaymentStatus
import online.afeibaili.storebackendframework.model.json.ProductJsonMapper
import online.afeibaili.storebackendframework.repository.OrderRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import kotlin.jvm.optionals.getOrElse


/**
 * 订单实现
 *
 *@author AfeiBaili
 *@version 2025/10/17 15:46
 */

@Service
@Transactional
class OrderServiceImpl {
    @Autowired
    lateinit var repository: OrderRepository

    @Autowired
    lateinit var shoppingCartServiceImpl: ShoppingCartServiceImpl

    fun create(order: OrderEntity): OrderEntity {
        val entity: OrderEntity = repository.save(order)
        return entity
    }

    fun createAndClearCart(order: OrderEntity): OrderEntity {
        val entity: OrderEntity = create(order)
        shoppingCartServiceImpl.clearProducts(order.accountId)
        return entity
    }

    fun getOrders(accountId: String): List<OrderEntity> {
        val entities: List<OrderEntity> = repository.findByAccountId(accountId)
        return entities
    }

    fun getProducts(orderId: Long): List<ProductJsonMapper> {
        val entity: OrderEntity = repository.findById(orderId).getOrElse {
            return listOf()
        }
        return ProductJsonMapper.toListObject(entity.products)
    }

    fun updatePayment(id: Long, paymentStatus: PaymentStatus): OrderEntity? {
        getById(id)?.let {
            it.paymentStatus = paymentStatus.code
            return it
        }
        return null
    }

    fun updatePaymentTime(id: Long, paymentTime: Long): OrderEntity? {
        getById(id)?.let {
            it.paymentTime = paymentTime
            return it
        }
        return null
    }

    fun updateShippingTime(id: Long, shippingTime: Long): OrderEntity? {
        getById(id)?.let {
            it.shippingTime = shippingTime
            return it
        }
        return null
    }

    fun updateCompletion(id: Long, completionTime: Long): OrderEntity? {
        getById(id)?.let {
            it.completionTime = completionTime
            return it
        }
        return null
    }

    fun getById(id: Long): OrderEntity? {
        return repository.findById(id).orElse(null)
    }
}